/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="patternConfig">
    <el-container v-if="!isShowSingle" >
        <div class="main-container" style="height: 100%;width: 100%;">
          <el-tabs v-model="editableTabsValue" type="card"  @edit="handleTabsEdit" :before-leave="beforeLeave" style="height: 100%;">
            <el-tab-pane
              :closable="true"
              :key="item.tabName"
              v-for="(item) in editableTabs"
              :label="item.title"
              :name="item.tabName"
            >
              <div class="panel-content" style="height: 100%;">
                <div style="height: 6%;">
                  <div class="route-filter-container" style="display:flex;">
                    <div class="filter">
                      <span class="header-span">{{$t('openatccomponents.greenwaveoptimize.name')}}：</span>
                      <el-input
                          clearable
                          size="small"
                          v-model="item.title"
                          style="width:70%;"
                          @change="onConditionChange"
                      />
                    </div>
                  </div>
                </div>
                <div style="height: 94%;" class="table-container">
                  <PatternTable ref="patterntable"
                                :isSingleCrossMode="isSingleCrossMode"
                                :isShowTableHeader="isShowTableHeader"
                                :tableColums="tableColums"
                                :devicesData="devicesData"
                                :maxTableHeight="maxTableHeight"
                                :opt="item.devs"
                                :isAllowedExpand="isAllowedExpand"
                                @onNewPatternListChange="onNewPatternListChange"/>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane key="add" name="add" :closable="false">
              <span slot="label" style="padding: 8px;font-size:20px;font-weight:bold;">
                  +
              </span>
            </el-tab-pane>
          </el-tabs>
        </div>
    </el-container>
    <div v-if="isShowSingle" style="height: 100%;" class="table-container">
      <PatternTable ref="patterntable"
                    :isSingleCrossMode="isSingleCrossMode"
                    :isShowTableHeader="isShowTableHeader"
                    :tableColums="tableColums"
                    :devicesData="devicesData"
                    :opt="opt.optPatternList && opt.optPatternList.length > 0 ? opt.optPatternList[0].devs : {}"
                    :isAllowedExpand="isAllowedExpand"
                    :maxTableHeight="maxTableHeight"
                    @onNewPatternListChange="onNewPatternListChange"/>
    </div>
    <PlanContent v-show="false"
        :schemeData="schemeData"
        :step="step"
        :zIndexObj="zIndexObj"
        ref="planContent"
        @handlePlanChart="handlePlanChart"
        @handlePatternTable="handlePatternTable"
        @ErrorOcurrred='onErrorOcurrred'
        @resetContentComponent="resetContentComponent"/>
  </div>
</template>

<script>
import PlanContent from './planContent'
import { getMessageByCode } from '../../../utils/responseMessage'
import PatternTable from './pattern/patternTable'
import dateObj from './utils.js'
import { GetDeviceByIds } from '../../../api/device.js'
import { getAllPatternOfDevs } from '../../../api/route'
const { monthsModel, daysModelCh, daysModelEn, datesModel, monthsModelEn, datesModelEn } = dateObj
export default {
  name: 'PatternConfig',
  components: {
    PatternTable,
    PlanContent
  },
  props: {
    agentids: {
      type: Array,
      default: () => []
    },
    opt: {
      type: Object,
      default: () => null
    },
    isShowTableHeader: {
      type: Boolean,
      default: true
    },
    isSingleCrossMode: {
      type: Boolean,
      default: false
    },
    tableColums: {
      type: Array,
      default: () => ['no', 'agentid', 'name', 'isused', 'patternid', 'offset', 'cycle', 'pattern']
    },
    isOnlyOneTab: {
      type: Boolean,
      default: true
    },
    isAllowedExpand: {
      type: Boolean,
      default: true
    },
    isShowSingle: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    agentids: {
      handler (val, old) {
        if (old && val.join('') === old.join('')) {
          return false
        }
        if (!val || val.length === 0) {
          console.log('ematy anentids:', val)
          return false
        }
        console.log('full anentids:', val)
        this.handeAgentidsChange()
      },
      immediate: true
    }
  },
  data () {
    return {
      devicesData: [],
      deviceIds: [],
      maxTableHeight: 200,
      chartData: {},
      months: monthsModel,
      days: [],
      dates: datesModel,
      planData: [],
      schemeData: [],
      step: false, // 控制第二个蒙层是否可以显示
      zIndexObj: {
        // 由于“新增”“编辑”均有蒙层，因此需动态改变可点击按钮层级
        addZIndex: 98,
        editZIndex: 98
      },
      reset: false,
      activeName: 'first',
      chooseId: 0, // 选中的计划id
      // agentids: [],
      // isOnlyOneTab: true,
      loading: false,
      keyintsidOptions: [],
      editableTabsValue: '1',
      routePattern: {
        'id': 1,
        'optPatternList': []
      },
      defaultOptPattern: {
        'tabName': '1',
        'month': [],
        patternid: 1,
        'day': [],
        'date': [],
        'plan': {
          'start': '11:00',
          'end': '13:00'
        },
        'optstrategy': 'green',
        'direction': 'up',
        'keyintsid': '',
        'upspeed': 0,
        'downspeed': 0,
        'devs': []
      },
      currentIndex: 0,
      editableTabs: [{
        title: '仿真实例 1',
        tabName: '1',
        content: 'Tab 1 content',
        patternid: 1,
        'month': [],
        'day': [],
        'date': [],
        'plan': {
          'start': '11:00',
          'end': '13:00'
        },
        'optstrategy': 'green',
        'direction': 'up',
        'keyintsid': '',
        'upspeed': 0,
        'downspeed': 0,
        'devs': []
      }],
      tabIndex: 1
    }
  },
  created () {
    this.resetTab()
    let lan = this.$i18n.locale
    if (lan === 'en') {
      this.days = daysModelEn
      this.dates = datesModelEn
      this.months = monthsModelEn
    }
    if (lan === 'zh') {
      this.days = daysModelCh
      this.dates = datesModel
      this.months = monthsModel
    }
  },
  mounted () {
    // let _this = this
    // _this.$nextTick(function () {
    //   _this.calcMaxTableHeight()
    // })
    this.calcMaxTableHeight()
  },
  methods: {
    calcMaxTableHeight () {
      let parentElement = this.$el.parentElement
      console.log('parentElement', parentElement)
      const clientHeight = parentElement.clientHeight
      console.log('clientHeight', clientHeight)
      const extHeight = this.isShowSingle ? 0 : 94
      this.maxTableHeight = clientHeight - extHeight - 1
      console.log('calcMaxTableHeight:', this.maxTableHeight)
      if (this.maxTableHeight < 150) {
        this.maxTableHeight = 200
        console.log('set default maxHeight 200', this.maxTableHeight)
      }
    },
    async handeAgentidsChange () {
      // this.calcMaxTableHeight()
      let devs = []
      for (let agentid of this.agentids) {
        let item = {
          agentid: agentid,
          patternid: 1,
          isused: true
        }
        devs.push(item)
      }
      let _this = this
      this.$nextTick(async () => {
        let route = {
          devs: devs
        }
        let optPatternList
        if (_this.opt && _this.opt.optPatternList && _this.opt.optPatternList.length > 0) {
          route = _this.opt.optPatternList[0]
          let arr = []
          for (let dev of route.devs) {
            arr.push(dev.agentid)
          }
          if (arr.length === this.agentids.length) {
            optPatternList = _this.opt.optPatternList
            let opt = await this.checkAndResetList(optPatternList)
            optPatternList = opt.optPatternList
          }
        }
        this.route = route
        await _this.getDeviceByIds(route)
        _this.onAgentidsChange('', optPatternList, _this.agentids)
      })
    },
    async checkAndResetList (optPatternList) {
      let res = JSON.parse(JSON.stringify(optPatternList))
      let resetFlag = false
      for (let opt of optPatternList) {
        if (opt.devs && opt.devs.length > 0) {
          for (let dev of opt.devs) {
            if (!dev.feature || !dev.feature.patternList) {
              if (!resetFlag) {
                resetFlag = true
              }
            } else {
              // reset ring flow
              let phases = dev.feature.phases
              if (phases && phases.length > 0) {
                let patternList = dev.feature.patternList
                for (let pattern of patternList) {
                  let rings = pattern.rings
                  if (rings && rings.length > 0) {
                    for (let ringList of rings) {
                      if (ringList && ringList.length > 0) {
                        for (let ring of ringList) {
                          let pahseItem = phases.find(item => item.id === ring.id)
                          if (pahseItem) {
                            ring = Object.assign(ring, pahseItem)
                            // ring = {...ring, ...pahseItem}
                            // console.log(ring)
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      if (resetFlag) {
        res = await this.getFullOptList(optPatternList)
      }
      return res
    },
    async getAllPatternOfRoute (agentids) {
      if (agentids.length === 0) return
      return new Promise((resolve, reject) => {
        getAllPatternOfDevs(agentids).then(res => {
          if (!res.data.success) {
            let agentid = res.data.data.agentid
            let commomMsg = this.$t('openatccomponents.greenwaveoptimize.device') + agentid
            let data = res
            let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
            if (data.data.data) {
              // 子类型错误
              let childErrorCode = data.data.data.errorCode
              if (childErrorCode) {
                let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
                this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
              }
            } else {
              this.$message.error(parrenterror + ',' + commomMsg)
            }
            console.error('ErrorOcurrred')
            resolve([])
          }
          let allPatternList = res.data.data.devs
          resolve(allPatternList)
        })
      })
    },
    async getFullOptList (optPatternList) {
      let allPatternList = await this.getAllPatternOfRoute(this.agentids)
      // console.log('allPatternList', allPatternList)
      let res = {
        'optPatternList': []
      }
      for (let i = 0; i < optPatternList.length; i++) {
        let opt = optPatternList[i]
        let opteItem = {
          'id': i + 1,
          'name': opt.name,
          title: opt.name,
          'tabName': i + 1 + '',
          'devs': []
        }
        for (let j = 0; j < opt.devs.length; j++) {
          let dev = opt.devs[j]
          let patternList = allPatternList.filter(ap => ap.agentid === dev.agentid)[0].feature.patternList
          let patternItem = patternList.filter(pattern => pattern.id === dev.patternid)[0]
          let devItem = {
            'agentid': dev.agentid,
            'patternid': dev.patternid,
            'isused': dev.isused,
            'id': j + 1,
            'offset': patternItem.offset,
            'cycle': patternItem.cycle,
            'patternId': patternItem.id,
            'desc': patternItem.desc,
            'patternDesc': patternItem.patternDesc,
            'feature': {
              'patternList': patternList
            }
          }
          opteItem.devs.push(devItem)
        }
        res.optPatternList.push(opteItem)
      }
      // console.log('getFullOptList', res)
      return res
    },
    handlePlanChart (routeData, patternList, greenwave, allPatternList) {
      let chartData = {
        routeData,
        patternList,
        greenwave,
        allPatternList
      }
      this.chartData = chartData
    },
    handlePatternTable (routeData, patternList, phaseList) {
      let index = this.currentIndex
      let patterntable = this.$refs.patterntable
      if (patterntable instanceof Array) {
        patterntable = this.$refs.patterntable[index]
      }
      patterntable.onPatternTable(routeData, patternList, phaseList)
    },
    onNewPatternListChange (newPatternList) {
      let list = JSON.parse(JSON.stringify(newPatternList))
      let editableTab = this.editableTabs[this.currentIndex]
      let devs = editableTab.devs
      let devList = []
      for (let dev of devs) {
        for (let pattern of list) {
          if (dev.agentid === pattern.agentid) {
            dev = {...dev, ...pattern}
            dev.isused = pattern.isused
            let allPatterns = pattern.allPatterns
            for (let p of allPatterns) {
              if (p.id === dev.patternid) {
                p.cycle = dev.cycle
                p.offset = dev.offset
                p.rings = dev.rings
              }
            }
            dev.patternList = JSON.parse(JSON.stringify(allPatterns))
            if (dev.feature && dev.feature.patternList) {
              dev.feature.patternList = JSON.parse(JSON.stringify(allPatterns))
            } else {
              let feature = {
                patternList: JSON.parse(JSON.stringify(allPatterns))
              }
              dev.feature = feature
            }
            devList.push(dev)
          }
        }
      }
      editableTab.devs = devList
      // this.refreshChart()
    },
    afterEnter () {
      if (this.chooseId === 0) {
        return false
      }
    },
    checkData (tabs, isCheckName = true) {
      let res = true
      if (this.agentids.length === 0) {
        this.$message.warning(this.$t('openatccomponents.greenwaveoptimize.chooseRoute'))
        return false
      }
      for (let tab of tabs) {
        if (!tab.devs || tab.devs.length === 0) {
          this.$message.warning(this.$t('openatccomponents.greenwaveoptimize.abnormalIntersections'))
          return false
        }
        // reset date
        this.resetDate(tab)
      }
      return res
    },
    getPatternConfig () {
      let res = this.getSaveParam(true)
      return res
    },
    getSaveParam (filter) {
      // check
      let check = this.checkData(this.editableTabs)
      if (!check) {
        return false
      }
      let routeData = this.editableTabs
      let planContent = this.$refs.planContent
      let params = planContent.getSaveParam(this.route.id, routeData, filter)
      return params
    },
    onSaveClick () {
      // check
      let check = this.checkData(this.editableTabs)
      if (!check) {
        return false
      }
      let routeData = this.editableTabs
      let planContent = this.$refs.planContent
      planContent.handleSave(this.route.id, routeData)
    },
    onDownSendClick () {
      let routeData = this.editableTabs[this.currentIndex]
      let check = this.checkData([routeData])
      if (!check) {
        return false
      }
      this.resetDate(routeData)
      let planContent = this.$refs.planContent
      planContent.handleDownload(this.route.id, routeData)
    },
    async onDeleteClick (targetName) {
      let routeData = this.editableTabs[this.currentIndex]
      // check
      let id = routeData.id
      if (targetName !== routeData.tabName) {
        this.$message.warning(this.$t('openatccomponents.greenwaveoptimize.choosePattern'))
        return false
      }
      if (this.editableTabs.length === 1) {
        this.$message.warning(this.$t('openatccomponents.greenwaveoptimize.atleastOnePattern'))
        return false
      }
      let optPatternList = this.route.optPatternList
      if (!optPatternList) {
        return true
      }
      let list = optPatternList.filter(item => item.id === id)
      if (list.length === 0) {
        return true
      } else {
        let planContent = this.$refs.planContent
        let param = {
          routeid: this.route.id,
          optpatternid: id
        }
        let flag = await planContent.handleDelete(param)
        return flag
      }
    },
    resetDate (tab) {
      let date = tab.date
      let day = tab.day
      let month = tab.month
      if (date && date.includes('全选')) {
        let index = date.indexOf('全选')
        date.splice(index, 1) // 排除全选选项
      } else if (date && date.includes('All')) {
        let index = date.indexOf('All')
        date.splice(index, 1) // 排除全选选项
      }
      if (day && day.includes(8)) {
        let index = day.indexOf(8)
        day.splice(index, 1) // 排除全选选项
      }
      if (month && month.includes(0)) {
        let index = month.indexOf(0)
        month.splice(index, 1) // 排除全选选项
      }
    },
    onConditionChange () {},
    beforeLeave (currentName, oldName) {
      // var self = this // 重点，如果name是add，则什么都不触发
      if (currentName === 'add') {
        if (this.agentids.length === 0) {
          this.$message.warning(this.$t('openatccomponents.greenwaveoptimize.chooseCros'))
          return false
        }
        if (this.isOnlyOneTab) {
          this.$message.warning(this.$t('openatccomponents.greenwaveoptimize.onlyOneTab'))
          return false
        }
        this.addTab()
        return false
      }
      for (let i = 0; i < this.editableTabs.length; i++) {
        let tab = this.editableTabs[i]
        if (tab.tabName === currentName) {
          this.currentIndex = i
          break
        }
      }
      this.initPatternList(this.chooseId, this.agentids)
    },
    addTab () {
      this.handleTabsEdit('', 'add')
    },
    async handleTabsEdit (targetName, action) {
      if (action === 'add') {
        let newTabName = ++this.tabIndex + ''
        let tabObj = {
          id: this.currentIndex + 1,
          name: '',
          title: this.$t('openatccomponents.greenwaveoptimize.scene') + ' ' + newTabName,
          tabName: newTabName,
          content: 'New Tab content',
          patternid: 1,
          'month': [],
          'day': [],
          'date': [],
          'plan': {
            'start': '08:00',
            'end': '09:30'
          },
          'optstrategy': 'green',
          'direction': 'up',
          'keyintsid': '',
          'upspeed': 0,
          'downspeed': 0,
          'devs': []
        }
        this.editableTabs.push(tabObj)
      }
      if (action === 'remove') {
        let flag = await this.onDeleteClick(targetName)
        if (!flag) {
          return false
        }
        let tabs = this.editableTabs
        let activeName = this.editableTabsValue
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.tabName === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.tabName
              }
            }
          })
        }
        this.editableTabsValue = activeName
        this.editableTabs = tabs.filter(tab => tab.tabName !== targetName)
      }
    },
    refresh () {
      // this.getAllPlan()
      let planContent = this.$refs.planContent
      if (planContent) {
        planContent.closeInterval()
        planContent.startInterval()
      }
    },
    editStart () {
      let planContent = this.$refs.planContent
      if (planContent && planContent.timer > 0) {
        planContent.closeInterval()
      }
    },
    maskChange (val) {
      // 控制两个蒙层下按钮的层级关系，并判断第二个蒙层显示的时机
      if (val) {
        this.step = false
        this.zIndexObj = {
          addZIndex: 99,
          editZIndex: 96
        }
      } else {
        this.step = true
        this.zIndexObj = {
          addZIndex: 96,
          editZIndex: 99
        }
      }
    },
    resetContentComponent () {
      // 每次切换侧边栏方案时，重置销毁planContent组件
      this.reset = false
      this.$nextTick(() => {
        this.reset = true
      })
    },
    resetTab () {
      this.editableTabs = [
        {
          title: this.$t('openatccomponents.greenwaveoptimize.scene') + ' 1',
          id: 1,
          name: '',
          tabName: '1',
          content: 'Tab 1 content',
          patternid: 1,
          'month': [],
          'day': [],
          'date': [],
          'plan': {
            'start': '08:00',
            'end': '09:30'
          },
          'optstrategy': 'green',
          'direction': 'up',
          'keyintsid': '',
          'upspeed': 0,
          'downspeed': 0,
          'devs': []
        }
      ]
      this.tabIndex = 1
      this.currentIndex = 0
      this.editableTabsValue = '1'
      this.keyintsidOptions = []
      this.chartData = {}
      // this.route = {}
      // this.agentids = []
    },
    onAgentidsChange (id, optPatternList, agentids) {
      // reset data
      if (agentids.length === 0) {
        return false
      }
      this.resetTab()
      this.chooseId = id
      // this.agentids = agentids
      // console.log('this.optPatternList', optPatternList)
      if (optPatternList && optPatternList.length > 0) {
        this.editableTabs = JSON.parse(JSON.stringify(optPatternList))
        // console.log('this.editableTabs', this.editableTabs)
      } else {
        // console.log(222)
        this.editableTabs[0].devs = this.route.devs
      }
      this.tabIndex = this.editableTabs.length
      this.initPatternList(id, agentids)
    },
    chooseRoute (id, route, agentids) {
      this.agentids = agentids
    },
    initPatternList (id, agentids) {
      let index = this.currentIndex
      let editableTab = this.editableTabs[index]
      let planContent = this.$refs.planContent
      if (planContent) {
        if (editableTab.devs && editableTab.devs.length === 0) {
          let devs = []
          for (let agentid of agentids) {
            let item = {
              agentid: agentid,
              isused: true,
              patternid: 1
            }
            devs.push(item)
          }
          let route = {
            devs: devs
          }
          editableTab = {...editableTab, ...route}
          editableTab.id = this.currentIndex + 1
        }
        if (this.editableTabs[index].devs.length === 0) {
          this.editableTabs[index] = editableTab
        }
        planContent.init(this.chooseId, editableTab, agentids)
      }
    },
    onErrorOcurrred () {
      this.resetTab()
      let patterntable = this.$refs.patterntable
      if (patterntable instanceof Array) {
        patterntable = patterntable[0]
      }
      patterntable.newPatternList = []
    },
    async getDeviceByIds (routeData) {
      // 获取设备表格信息
      let realtimeRouteData = JSON.parse(JSON.stringify(routeData))
      let findItem = realtimeRouteData.devs.find(item => !item.name)
      if (!findItem) {
        this.devicesData = realtimeRouteData.devs
        return false
      }
      this.deviceIds = realtimeRouteData.devs.map(ele => ele.agentid)
      await GetDeviceByIds(this.deviceIds).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.devicesData = res.data.data
        // // 取路口对应的实际方案id
        // let devs = realtimeRouteData.devs
        // for (let inter of devs) {
        //   inter.patternid = this.getActurlPatternid(inter.agentid)
        // }
        // this.chartData.realPatternRouteData = realtimeRouteData
        // this.$refs.chartDialog.show(true, this.chartData, this.route.name, this.devicesData)
      })
    // },
    // getActurlPatternid (agentid) {
    //   let devinfo = this.devicesData.filter(dev => dev.agentid === agentid)[0]
    //   if (devinfo.patternid !== undefined) {
    //     return devinfo.patternid
    //   } else {
    //     return 1
    //   }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button--primary.is-plain:active{
  color: #fff;
}
.el-button--primary.is-plain:hover, .el-button--primary.is-plain:focus{
  color: #fff;
}
>>> .el-tabs__header {
  padding: 0;
  position: relative;
  margin: 0 0 0px;
}
</style>
